let axios = require('axios');
let fs = require('fs')
let cheerio = require('cheerio');
let QianKaDBController = require('./db/QianKaDBController')
class qianka {
  constructor(key) {
    this.app = {}
    this.userArr = {
      t1: {
        phone: '13279441484',
        name: 'T1-17135079549',//微信昵称
        cookie: `DIS4=a31b8624d2b04bf7bde2af858d850345; _umdata=GEEE1C5357C95772475AC12F282D7A70358487B; Hm_lpvt_484788504bd0bc163a54b110d0dc003c=1548384647; Hm_lvt_484788504bd0bc163a54b110d0dc003c=1548384647; _uab_collina=154838464695361792520556; lite_token=dc990cf42d0a0115c4dea1d14df936ae; ln=1; lu=62163103; user_redirct_subtask_list=1`,
        remarks:'阿里小号'
      }
    }
    this.user = this.userArr[key]
    this.headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Host': 'qianka.com',
      'Cookie': this.user.cookie,
      'Accept': 'application/json, text/plain, */*',
      'User-Agent': `Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C101 version=2.0.2018091801 bid=com.kka.video`
    }


    this.instance = axios.create({
      baseURL: 'https://qianka.com',
      headers: this.headers
    });

    this.db = new QianKaDBController('qianka0')
    try {
      this.db.create()
    } catch (err) {
      console.log('表存在!')
    }
  }

  applyTask(id, cb) {
    console.log('任务申请中...')
    this.instance.get(`https://qianka.com/s4/lite.subtask.start?task_id=${id}&quality=0`).then(res => {
      console.log(res.data)
    }).catch(err => {
      console.log(err)
    })
  }

  getTaskList(cb) {
    this.instance.get(`/s4/lite.subtask.list`).then(res => {
      cb({
        success: true,
        res
      })
    }).catch(err => {
      cb({
        success: false,
        err
      })
    })
  }


  tasksScanning() {
    console.log('正在扫描任务...')
    this.getTaskList(data => {
      this.newTaskId = 0
      if (data.success) {
        let tasks = data.res.data.payload.tasks || [];
        let flag = false;

        this.tasks = [];
        for (let i = 0; i < tasks.length; i++) {
          if (tasks[i].is_pay === 0) {
            this.tasks.push(tasks[i]);
          }
          if (tasks[i].status === 2) {
            flag = true;
            this.currentTaskId = tasks[i].id;
            this.currentTaskIndex = i;
          }
        }
        // console.log(this.tasks)
        //对this.tasks进行算法，并排序//TODO
        if (this.tasks.length && flag === false && this.tasks[0].qty > 0) {
          this.newTaskId = this.tasks[0].id;
          console.log(`发现新任务:${this.tasks[0].title}:${this.newTaskId}`);
          // this.applyTask(this.newTaskId)
        } else if (flag === true) {
          console.log(`任务${this.currentTaskId}进行中...`)
          console.log(`appurl:${this.app.url}`)
          this.getTaskDetail();
          // return false;
        } else if (this.tasks.length === 0) {
          console.log('暂无任务')
        } else {
          console.log('暂无任务1')
        }
      } else {
        console.error(data.err)
      }
      setTimeout(() => {
        this.tasksScanning();
      }, 5000)
    })
  }

  getTaskDetail() {
    this.taskDetail = {}
    this.instance.get(`/s4/lite.subtask.detail?task_id=${this.currentTaskId}`).then(res => {
      // console.log(res.data)
      this.taskDetail = res.data.payload;
      this.searchAppUrl();
      console.log(`appName:${this.taskDetail.app_name}`)
    }).catch(err => {
      console.log(err)
    })
  }

  singIn() {
    console.log('开始签到...');
    this.instance.post(`/s5/reward.coin.claim.today`).then(res => {
      console.log('签到成功!!!')
      setTimeout(() => {
        this.singIn()
      }, 2000)
    }).catch(err => {
      console.log(err.response.data.err_msg)
      if (err.response && err.response.data && err.response.data.err_msg && err.response.data.err_msg === '今日已经领取过了') {
        console.log('已签到!!!')
      } else {
        setTimeout(() => {
          this.singIn()
        }, 2000)
      }
    })
  }

  searchAppUrl() {
    // 口碑-美食外卖，点餐订餐平台
    console.log('searchAppUrl...')
    if (!(this.app && this.app.name === this.taskDetail.app_name)) {
      axios.get(encodeURI(`https://www.chandashi.com/search/index?keyword=${this.taskDetail.app_name.split(/[—（,]/)[0]}&type=store&country=cn`)).then(res => {
        try {
          let $ = cheerio.load(res.data);
          let list = $('#searchlist .search-list-item');
          if (list && list.length) {
            let index = -1;
            for (let i = 0; i < list.length; i++) {
              let title = $(list[i]).find('a').attr('title').replace(/\s/g, '')
              if (title === this.taskDetail.app_name.replace(/\s/g, '')) {
                index = i;
                break;
              }
            }
            if (index !== -1) {
              this.app.id = $(list[index]).find('a').attr('href').match(/\/appId\/\d+?\/country/)[0].match(/\d+/)[0]
            } else {
              this.app.id = $(list[0]).find('a').attr('href').match(/\/appId\/\d+?\/country/)[0].match(/\d+/)[0]
            }
            this.app.name = this.taskDetail.app_name;
            this.app.url = `https://itunes.apple.com/cn/app/id${this.app.id}`
            console.log(`appurl:${this.app.url}`)
            let taskList = JSON.parse(fs.readFileSync('./dist/task.json') || '[]');
            taskList.push({
              sendName: this.user.name,
              appid: this.app.id,
              appName: this.taskDetail.app_name,
              appSrc: this.app.url
            })
            let data = [this.user.name, this.taskDetail.app_name, this.app.url, 0];
            this.db.insert(data)
            fs.writeFileSync('./dist/task.json', JSON.stringify(taskList));
          }
        } catch (err) {
          console.log(err)
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }

  init() {
    this.tasksScanning();
    // this.singIn();
    // this.currentTaskId = 256897
    // this.getTaskDetail()
  }
}


new qianka('t1').init();
